#!/usr/bin/python
# -*- coding:utf-8 -*-
# @FileName : dp_test2_2.py
# Author    : myh

# encoding:gbk
import numpy as np
import torch
import matplotlib.pyplot as plt
import os

os.environ['KMP_DUPLICATE_LIB_OK'] = 'True'

x = torch.arange(4.0)
print(x)




x.requires_grad_(True)
print(x.grad)
# (0+1+4+9)*2
y = 2 * torch.dot(x, x)
print(y)
y.backward()
print(x.grad)

# 在默认情况下，PyTorch会累积梯度，我们需要清除之前的值
x.grad.zero_()
y = x.sum()
y.backward()
print(x.grad)
y.backward()
print(x.grad)



x = np.linspace(-3*np.pi, 3*np.pi, 100)
x1 = torch.tensor(x)
x1.requires_grad = True
y1 = torch.sin(x1)
y1.sum().backward()

plt.plot(x, np.sin(x))
print(x1)
print(x1.grad)

y2 = 2*x1
x1.grad.zero_()
y2.sum().backward()
plt.plot(x, x1.grad)
print(y1)
plt.show()


